package api

import (
	"github.com/gin-gonic/gin"
	"math/rand"
	"path/filepath"
	"seat-service/middleware"
	"seat-service/model"
	"seat-service/model/dto"
	"seat-service/response"
	service "seat-service/service/impl"
	"strconv"
)

var information service.InformationService

type InformationApi struct {
}

func (*InformationApi) QueryInformation(c *gin.Context) {
	id := c.Query("student_id")

	numId, _ := strconv.Atoi(id)
	student, err := information.QueryInformation(uint(numId))
	if err != nil {
		response.Fail(c, response.DatabaseException, nil)
		return
	}
	response.Success(c, response.CodeSuccess, student)
}

func (*InformationApi) RecordInformation(c *gin.Context) {
	id := c.Query("student_id")
	page := c.Query("page")
	pageSize := c.Query("page_size")
	numId, _ := strconv.Atoi(id)
	p, _ := strconv.Atoi(page)
	ps, _ := strconv.Atoi(pageSize)
	reserve, err := information.RecordInformation(uint(numId), uint(p), uint(ps))
	if err != nil {
		response.Fail(c, response.DatabaseException, nil)
		return
	}
	response.Success(c, response.CodeSuccess, reserve)
}

func (*InformationApi) FeedbackInformation(c *gin.Context) {
	var feedback dto.RecordFeedbackDto
	err := c.ShouldBindJSON(&feedback)
	if err != nil {
		response.Fail(c, response.CodeParamError, nil)
		return
	}
	numId, _ := strconv.Atoi(feedback.StudentId)
	err = information.FeedbackInformation(model.Feedback{
		StudentId: uint(numId),
		Content:   feedback.Content,
	})
	if err != nil {
		response.Fail(c, response.DatabaseException, nil)
		return
	}
	response.Success(c, response.CodeSuccess, nil)

}

func (*InformationApi) UpHead(c *gin.Context) {
	file, err := c.FormFile("file")
	if err != nil {
		response.Fail(c, response.DataInWrongFormat, nil)
		return
	}
	uploadDir := "./uploads/head"
	name := file.Filename
	a := rand.Intn(1000) + 1
	file.Filename = strconv.Itoa(a) + name
	// 生成保存文件的完整路径
	filePath := filepath.Join(uploadDir, file.Filename)

	// TODO 保存文件
	err = c.SaveUploadedFile(file, filePath)
	if err != nil {
		response.Fail(c, response.ServerException, nil)
		return
	}
	id, _ := c.Get("id")
	sID := id.(uint)
	err = information.UpHead(filePath, sID)
	if err != nil {
		response.Fail(c, response.DatabaseException, nil)
		return
	}
	response.Success(c, response.CodeSuccess, filePath)
}

// CreditRecordInformation 学生信誉记录查询
func (*InformationApi) CreditRecordInformation(c *gin.Context) {
	id, exists := c.Get(middleware.UserId)
	if !exists {
		response.Fail(c, response.CodeUserNoExit, nil)
		return
	}
	sID := id.(uint)
	count1, count2, err := information.CreditRecordInformation(sID)
	if err != nil {
		response.Fail(c, response.CreditRecordInformationNoExist, nil)
	}
	response.Success(c, response.CodeSuccess, gin.H{
		"total_record":    count1,
		"violation_count": count2,
	})
}
